package org.liaohailong.library.widget.shopping.recycler;

import android.util.SparseArray;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.LinkedList;

/**
 * Author: Victor
 * E-mail: liaohailong190@foxmail.com
 * Date: 2019/6/22 16:40
 * Description: 二级缓存
 */
public class Recycler {

    /**
     * 一级缓存，添加过的视图暂时缓存区
     * key = ItemViewType
     */
    private SparseArray<LinkedList<View>> mScrapViews = new SparseArray<>();

    /**
     * 二级缓存，一段时间内可能都不会再显示的缓存区
     * key = AdapterIndex
     */
    private SparseArray<RecyclerPool> mRecyclerPool = new SparseArray<>();


    public void addScrapView(int viewType, View view) {
        LinkedList<View> views = mScrapViews.get(viewType);
        if (views == null) {
            views = new LinkedList<>();
            mScrapViews.put(viewType, views);
        }
        views.addLast(view);
    }

    @Nullable
    public View getScrapView(int viewType) {
        LinkedList<View> views = mScrapViews.get(viewType);
        if (views == null) {
            views = new LinkedList<>();
            mScrapViews.put(viewType, views);
        }
        return views.removeFirst();
    }

    public void setRecyclerPool(int index, RecyclerPool recyclerPool) {
        mRecyclerPool.put(index, recyclerPool);
    }

    public void recycleView(int adapterIndex, int viewType, View view) {
        RecyclerPool recyclerPool = mRecyclerPool.get(adapterIndex);
        recyclerPool.recycleView(viewType, view);
    }

    public View obtainRecycledView(int adapterIndex, int viewType) {
        RecyclerPool recyclerPool = mRecyclerPool.get(adapterIndex);
        return recyclerPool.obtainView(viewType);
    }


}
